<?php

namespace app\admin\controller;

use app\admin\controller\CommonController;
use think\Validate;
use think\Db;
use app\admin\model\Store;
use app\admin\model\ProvCityArea;
use app\admin\model\TradingLabel;
use app\admin\model\StaffBindStore;
use app\admin\model\Yuyue;
use app\admin\model\Staff;
use app\admin\model\StoreStaff;
use app\admin\model\ServiceNews;
use app\util\Utils;
use app\admin\model\StoreBed;
use app\admin\model\StoreImg;
use app\admin\model\StoreCostInput;
use app\util\Callout;
use app\admin\model\StoreApply;
use app\util\File;
use app\admin\model\StaffCtm;
use app\admin\model\Custom;
use app\admin\model\StaffNote;
use app\admin\model\Order;
use app\admin\model\CtmCollect;
use app\admin\model\StoreCtm;
use app\admin\model\CtmSpecial;
use app\admin\model\MedicalAddress;
use app\admin\model\StoreSoldoutitem;
use app\admin\model\Item;
use app\admin\model\Overgroup;
use app\admin\model\Miaosha;

class StoreController extends CommonController {
    /*
     * 所有店铺的列表
     * author xfwed 
     * date 2019.09.21
     */

    public function allStoreList() {
        $list = Store::where('is_del', '=', 1)->field('id,store_name')->select();
        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 店铺列表
     * author xfwed 
     * date 2019.09.21
     */

    public function storeList() {
        $status = input('param.status');
        $cityId = input('param.cityId');
        $trading = input('param.trading');
        $storeName = input('param.storeName');
        $phone = input('param.phone');
        $is_open = input('param.is_open');
        $is_del = input('param.is_del');
        $perPage = input('param.perPage');
        $page = input('param.page');
        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        $pData = ProvCityArea::where('id', '=', $cityId)->field('level,pid')->find();
        $level = $pData['level'];
        $pid = $pData['pid'];
        $prov = '';
        $city = '';
        $area = '';
        $warning_level = input('param.warning_level');//预警等级-1全部 0正常  1红色预警  2黄色预警
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');
        $store_type = input('param.store_type');//店铺类型 0全部 1品牌连锁店 2服务授权店
        if ($level == 1) {
            $prov = $cityId;
        } elseif ($level == 2) {
            $city = $cityId;
        } elseif ($level == 3) {
            //$area = $cityId;
            $city = $pid;
        }

        if ($status) {//审核状态 0未审核 1审核通过 2审核不通过	
            $where['auditstore'] = $status;
        }
        if($status == -1){
            $where['auditstore'] = 0;
        }

        if ($prov) {
            $where['prov'] = $prov;
        }

        if ($city) {
            $where['city'] = $city;
        }

        if ($area) {
            $where['area'] = $area;
        }

        if ($trading) {
            $where['store_trading'] = $trading;
        }

        if ($storeName) {
            $where['store_name'] = ['like', '%' . $storeName . '%'];
        }

        if ($phone) {
            $where['keeper_phone'] = $phone;
        }
        if ($is_open) {
            $where['is_open'] = $is_open;
        }
        if ($is_del) {
            $where['is_del'] = $is_del;
        }
        if(preg_match("/^[0-9][0-9]*$/" ,$warning_level)){
            $where['warning_level'] = $warning_level;
        }
        if($start_time && $end_time){
            $where['add_time'] = ['between',[$start_time,$end_time]];
        }
        if($store_type){
            $where['type'] = $store_type;
        }

        $where = isset($where) ? $where : [];

        $storeList = Store::where($where)
                        ->field('id,store_name,store_keeper,keeper_phone,logoimg,city,store_trading,store_scale,bed_num,auditstore,add_time,money,tx_money,auditstore,is_open,open_time,warning_level,type store_type')
                        ->paginate($perPage)->toArray();

        foreach ($storeList['data'] as $k => $v) {
            $storeList['data'][$k]['cityName'] = ProvCityArea::cityName($v['city']);
            $storeList['data'][$k]['tradingName'] = TradingLabel::where('id', '=', $v['store_trading'])->value('name');
            $storeList['data'][$k]['staffNum'] = StaffBindStore::where('store_id', '=', $v['id'])->count();

            $staff_ids = StaffBindStore::where('store_id', $v['id'])->column('staff_id');
            $staff_ids = implode(",", $staff_ids);

//            $storeList['data'][$k]['ctmNum'] = StaffCtm::alias('s')
//                    ->join('staff st', 'st.id = s.staff_id', 'left')
//                    ->where('s.staff_id', 'in', $staff_ids)
//                    ->group('s.ctm_id')
//                    ->count();
            $where1['s.store_id'] = $v['id'];
            $storeList['data'][$k]['ctmNum'] = StoreCtm::alias('s')
                ->join('staff st', 'st.id = s.staff_id', 'left')
                ->where($where1)
                ->group('s.ctm_id')
                ->count();
            //$storeList['data'][$k]['ctmNum'] = Yuyue::where('store_id', '=', $v['id'])->where('status', '=', 4)->group('ctm_id')->count();
        }
        return $this->ajaxReturn(0, '查询成功', $storeList);
    }

    /*
     * 添加店铺
     * author xfwed 
     * date 2019.09.27
     */

    public function addStore() {
        $rule = [
            'store_name' => 'require',
            'store_phone' => 'require',
            'store_address' => 'require',
            'store_scale' => 'require',
            'bed_num' => 'require',
            'store_keeper' => 'require',
            'keeper_phone' => 'require|length:11',
            'keeper_idcard' => 'require',
            'idcard1' => 'require',
            'idcard2' => 'require',
            'idcard3' => 'require',
            'bus_licence' => 'require',
            'longitude' => 'require',
            'latitude' => 'require',
            'logoimg' => 'require',
            'introduce' => 'require',
            'busstarttime' => 'require',
            'busendtime' => 'require',
            'prov' => 'require',
            'city' => 'require',
            'area' => 'require',
            'store_trading' => 'require',
            'type' => 'require',
        ];
        $msg = [
            'store_name.require' => '店铺名称必须',
            'store_phone.require' => '店铺电话必须',
            'store_address.require' => '店铺地址必须',
            'store_scale.require' => '店铺规模（平米）必须',
            'bed_num.require' => '店铺床位必须',
            'store_keeper.require' => '负责人姓名必须',
            'keeper_phone.require' => '负责人电话必须',
            'keeper_phone.length' => '负责人电话为11位',
            'keeper_idcard.require' => '负责人身份证号必须',
            'idcard1.require' => '身份证正面必须',
            'idcard2.require' => '身份证反面必须',
            'idcard3.require' => '手持身份证必须',
            'bus_licence.require' => '营业执照状态 1有 2无	必须',
            'longitude.require' => '经度必须',
            'latitude.require' => '纬度必须',
            'logoimg.require' => '店铺logo图片必须',
            'introduce.require' => '店铺简介必须',
            'busstarttime.require' => '营业开始时间必须',
            'busendtime.require' => '营业结束时间必须',
            'prov.require' => '省id必须',
            'city.require' => '市id必须',
            'area.require' => '市id必须',
            'store_trading.require' => '店铺商圈必须',
            'type.require' => '店铺类型必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        //生成店铺邀请码
        $invite_code = Store::generateInviteCode();
        $data['from'] = 1;
        $data['store_name'] = $all['store_name'];
        $data['store_phone'] = $all['store_phone'];
        $data['store_address'] = $all['store_address'];
        $data['store_scale'] = $all['store_scale'];
        $data['bed_num'] = $all['bed_num'];
        $data['store_keeper'] = $all['store_keeper'];
        $data['keeper_phone'] = $all['keeper_phone'];
        $data['keeper_idcard'] = $all['keeper_idcard'];
        $data['idcard1'] = $all['idcard1'];
        $data['idcard2'] = $all['idcard2'];
        $data['idcard3'] = $all['idcard3'];
        $data['bus_licence'] = $all['bus_licence'];
        $data['longitude'] = $all['longitude'];
        $data['latitude'] = $all['latitude'];
        $data['logoimg'] = $all['logoimg'];
        $data['introduce'] = $all['introduce'];
        $data['busstarttime'] = $all['busstarttime'];
        $data['busendtime'] = $all['busendtime'];
        $data['auditstore'] = 1;
        $data['prov'] = $all['prov'];
        $data['city'] = $all['city'];
        $data['area'] = $all['area'];
        $data['store_trading'] = $all['store_trading'];
        $data['store_type'] = 2;
        $data['add_time'] = date('Y-m-d H:i:s');
        $data['is_open'] = 2;
        $data['invite_code'] = $invite_code;
        if ($all['bus_licence'] == 1) {
            $data['bus_licence_type'] = $all['bus_licence_type'];
            $data['bus_licence_number'] = $all['bus_licence_number'];
            $data['bus_licence_start'] = $all['bus_licence_start'];
            $data['bus_licence_end'] = $all['bus_licence_end'];
            $data['bus_licence_name'] = $all['bus_licence_name'];
            $data['bus_licence_img'] = $all['bus_licence_img'];
        }
        $data['type'] = $all['type'];
        $row = Staff::where('telephone', $all['keeper_phone'])
                ->where('staff_on', 1)
                ->where('staff_is_creator', 0)
                ->field('id')
                ->find();
        if ($row) {
            return $this->ajaxReturn(3, '手机号已经注册美容师', null);
        }

        Db::startTrans();
        $insertId = Store::insertGetId($data);

        //插入美容师表
        $staffRow = Staff::where('telephone', $all['keeper_phone'])
                ->where('staff_on', 1)
                ->where('staff_is_creator', 1)
                ->field('id')
                ->find();
        if ($staffRow) {
            $staffInsertId = $staffRow['id'];
        } else {
            $staffdata['staff_name'] = $all['store_keeper'];
            $staffdata['telephone'] = $all['keeper_phone'];
            $staffdata['staff_pwd'] = strtoupper(md5($all['keeper_phone']));
            $staffdata['idcard1'] = $all['idcard1'];
            $staffdata['idcard2'] = $all['idcard2'];
            $staffdata['idcard_num'] = $all['keeper_idcard'];
            $staffdata['prov'] = $all['prov'];
            $staffdata['city'] = $all['city'];
            $staffdata['area'] = $all['area'];
            $staffdata['staff_photo'] = 'http://47.104.83.107/images/kkmimg/kkmai/default/photo.png';
            $staffdata['staff_is_creator'] = 1;
            $staffdata['status'] = 1;
            $staffdata['is_job'] = 2;
            $staffdata['login_time'] = date('Y-m-d H:i:s');
            $staffdata['add_time'] = date('Y-m-d H:i:s');
            $staffInsertId = Staff::insertGetId($staffdata);
        }

        $storeStaffInsertId = StoreStaff::insertGetId([
                    'staff_id' => $staffInsertId,
                    'store_id' => $insertId,
                    'login_time' => date('Y-m-d H:i:s'),
        ]);
        //生成店铺小程序码
        $file = new File();
        $xcxcode = $file->generateXcxcode($insertId);
        $qrcodeResult = Store::where('id', '=', $insertId)->update([
            'xcxcode' => $xcxcode,
        ]);
        //下架店铺不卖的项目
        $insertdata['store_id'] = $insertId;
        $insertdata['item_ids'] = '5,11,13,15,16,19,20,21,28,29,35,36,37,38,40,42';
        $insertdata['add_time'] = date('Y-m-d H:i:s');
        $StoreSoldoutitemResult = StoreSoldoutitem::insert($insertdata);


        if ($insertId && $staffInsertId && $storeStaffInsertId && $qrcodeResult && $StoreSoldoutitemResult) {
            $newsRow = ServiceNews::insert([
                        'titleid' => 1,
                        'otherid' => 0,
                        'content' => '很兴奋地告诉您又有一个新店铺入驻了，赶快去绑定吧',
                        'userid' => $staffInsertId,
                        'type' => 1,
                        'store_id' => $insertId,
                        'add_time' => date('Y-m-d H:i:s'),
            ]);
            $ApiPath = config('appconfig.ApiPath8890');
            $stafflist = Staff::where('city', $all['city'])->column('telephone');
            $postFields['content'] = '很兴奋地告诉您又有一个新店铺入驻了，赶快去绑定吧';
            $postFields['type'] = 0; //0新店上新7提现
            $postFields['titleId'] = 1; //1店铺动态2预约消息3营收消息
            $postFields['otherId'] = 0; //新店上新就是0
            $postFields['staffId'] = 0;
            $postFields['storeId'] = $insertId;
            if (count($stafflist) == 1) {
                $postFields['phone'] = $stafflist[0];
                $relust = Utils::curlPost($ApiPath . 'push/pushMessage/', json_encode($postFields));
//                print_r($relust);
            } elseif (count($stafflist) > 1) {
                $postFields['phones'] = $stafflist;
                $relust = Utils::curlPost($ApiPath . 'push/pushMessageList/', json_encode($postFields));
//                print_r($relust);
            }
            //给店铺开通小店
            //$ApiPath8891 = config('appconfig.ApiPath');
            //$relust = Utils::curlPost($ApiPath8891 . '/smallshop/storeAndStaffOpenShop/'.$insertId.'/2/0');
            Db::commit();
            return $this->ajaxReturn(0, '店铺添加成功', null);
        } else {
            Db::rollback();
            return $this->ajaxReturn(3, '店铺添加失败', null);
        }
    }

    /*
     * 店铺详情
     * author xfwed 
     * date 2019.09.28
     */

    public function storeInfo() {
        $id = input('param.id');
        //基本信息
        $storeRow = Store::where('id', $id)
                ->field('id,store_name,store_keeper,keeper_phone,store_trading,busstarttime,busendtime,bus_licence,bus_licence_number,bus_licence_start,bus_licence_end,store_address,idcard1,idcard2,idcard3,bus_licence_img,note,store_scale,bed_num,area,invite_code')
                ->find();
        $storeRow['cityName'] = ProvCityArea::areaName($storeRow['area']);
        $storeRow['tradingName'] = TradingLabel::where('id', '=', $storeRow['store_trading'])->value('name');
        //床位数
        $storeRow['bedList'] = StoreBed::where('store_id', $id)->field('bed_num,num')->select();
        //美容师数量
        $storeRow['staffNum'] = StaffBindStore::where('store_id', $id)->count();
        //客户数量
        $staff_ids = StaffBindStore::where('store_id', $id)->column('staff_id');
        $staff_ids = implode(",", $staff_ids);

        $storeRow['ctmNum'] = StaffCtm::alias('s')
                ->join('staff st', 'st.id = s.staff_id', 'left')
                ->where('s.staff_id', 'in', $staff_ids)
                ->group('s.ctm_id')
                ->count();
        //$storeRow['ctmNum'] = Yuyue::where('store_id', $id)->group('ctm_id')->count();
        //照片展示
        $imgList = StoreImg::where('store_id', $id)->field('img,type')->select();
        foreach ($imgList as $k => $v) {
            $imgList[$k]['typeName'] = action('admin/PublicController/imgClassList', ['id' => $v['type']]);
        }
        $storeRow['imgList'] = $imgList;
        //店铺投入
        $storeCostInputList = StoreCostInput::where('store_id', $id)->field('type,money,note,input_time,add_time')->select();
        foreach ($storeCostInputList as $k => $v) {
            $storeCostInputList[$k]['typeName'] = action('admin/PublicController/StoreCostInputList', ['id' => $v['type']]);
        }
        $storeRow['storeCostInputList'] = $storeCostInputList;
        $storeRow['allInout'] = StoreCostInput::where('store_id', $id)->sum('money');
        return $this->ajaxReturn(0, '查询成功', $storeRow);
    }

    /*
     * 店铺美容师列表
     * author xfwed 
     * date 2019.09.28
     */

    public function storeStaffList() {
        $id = input('param.id');
        $perPage = input('param.perPage');
        $page = input('param.page');
        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        $storeStaffList = StaffBindStore::alias('b')
                ->join('staff s', 's.id = b.staff_id', 'left')
                ->join('staff_rank r', 'r.id = s.staff_rank', 'left')
                ->field('s.id,s.staff_name,s.telephone,s.staff_year,s.cert_img,s.add_time,s.staff_on,s.is_job,s.money,s.tx_money,r.name,b.add_time')
                ->where('b.store_id', $id)
                ->paginate($perPage);

        return $this->ajaxReturn(0, '查询成功', $storeStaffList);
    }

    /*
     * 店铺用户列表
     * author xfwed 
     * date 2019.09.28
     */

//    public function storeCtmList() {
//        $id = input('param.id');
//        $perPage = input('param.perPage');
//        $page = input('param.page');
//        $perPage = isset($perPage) ? $perPage : 10;
//        $page = isset($page) ? $page : 1;
//        $storeCtmList = Yuyue::alias('y')
//                ->join('custom c', 'c.id = y.ctm_id', 'left')
//                ->field('c.id,c.custom_phone,c.custom_name,c.vip_status,c.add_time')
//                ->where('y.store_id', $id)
//                ->where('y.status', 'in', '4,7,8')
//                ->group('y.ctm_id')
//                ->paginate($perPage);
//
//        return $this->ajaxReturn(0, '查询成功', $storeCtmList);
//    }

    /*
     * 修改店铺床位
     * author xfwed 
     * date 2019.09.28
     */

    public function saveStoreBed() {
        $id = input('param.id');
//        $a = [['bed_num'=>1,'num'=>3],['bed_num'=>2,'num'=>2],['bed_num'=>3,'num'=>1]];
//        $a= json_encode($a);
//        print_r($a);die;
        $data = input('param.data');
        $data = json_decode($data, true);
        StoreBed::where('store_id', $id)->delete();
        $num = 0;
        foreach ($data as $k => $v) {
            StoreBed::insert(['store_id' => $id, 'bed_num' => $v['bed_num'], 'num' => $v['num'], 'add_time' => date('Y-m-d H:i:s')]);
            $num = $num + $v['bed_num'] * $v['num'];
        }
        Store::where('id', $id)->update(['bed_num' => $num]);
        return $this->ajaxReturn(0, '修改成功', null);
    }

    /*
     * 添加店铺照片
     * author xfwed 
     * date 2019.09.28
     */

    public function addStoreImg() {
        $id = input('param.id');
        $type = input('param.type');
        $img = input('param.img');
        $add = StoreImg::insert([
                    'store_id' => $id,
                    'type' => $type,
                    'img' => $img,
                    'add_time' => date('Y-m-d H:i:s')
        ]);
        if ($add) {
            return $this->ajaxReturn(0, '添加成功', null);
        } else {
            return $this->ajaxReturn(3, '添加失败', null);
        }
    }

    /*
     * 添加店铺备注
     * author xfwed 
     * date 2019.09.28
     */

    public function addStoreNote() {
        $id = input('param.id');
        $note = input('param.note');
        $save = Store::where('id', $id)->update(['note' => $note]);

        if ($save) {
            return $this->ajaxReturn(0, '添加成功', null);
        } else {
            return $this->ajaxReturn(3, '添加失败', null);
        }
    }

    /*
     * 添加店铺投入
     * author xfwed 
     * date 2019.09.28
     */

    public function addStoreInput() {
        $id = input('param.id');
        $type = input('param.type');
        $money = input('param.money');
        $note = input('param.note');
        $input_time = input('param.input_time');
        $add = StoreCostInput::insert([
                    'store_id' => $id,
                    'type' => $type,
                    'money' => $money,
                    'note' => $note,
                    'input_time' => $input_time,
                    'add_time' => date('Y-m-d H:i:s')
        ]);
        if ($add) {
            return $this->ajaxReturn(0, '添加成功', null);
        } else {
            return $this->ajaxReturn(3, '添加失败', null);
        }
    }

    /*
     * 外呼 拨打电话
     * author xfwed
     * date 2019.10.09
     */

    public function CallOut() {
        $phone = input('param.phone');
        $jobnum = input('param.jobnum');
        $Callout = new Callout();
        $result = $Callout->call($phone, $jobnum);
        $result = json_decode($result, true);
        $status = $result['Succeed'];
        if ($status) {
            return $this->ajaxReturn(0, '拨打成功', $result);
        } else {
            $message = $result['Message'];
            return $this->ajaxReturn(1, $message, $result);
        }
    }

    /*
     * 店铺加盟申请列表
     * author xfwed 
     * date 2019.10.17
     */

    public function storeApplyList() {
        $phone = input('param.phone');
        $name = input('param.name');
        $perPage = input('param.perPage');
        $page = input('param.page');
        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        if ($phone) {
            $where['phone'] = $phone;
        }

        if ($name) {
            $where['name'] = $name;
        }
        $where = isset($where) ? $where : [];

        $storeList = StoreApply::where($where)->order('add_time desc')->paginate($perPage);

        return $this->ajaxReturn(0, '查询成功', $storeList);
    }

    /*
     * 添加/修改备注
     * author xfwed
     * date 2019-10-17     
     */

    public function SaveMsg() {
        $id = input('param.id');
        $adminname = input('param.adminname');
        $note = input('param.note');
        $storerow = StoreApply::where('id', '=', $id)->field('note')->find();

        $msg = date("Y-m-d H:i:s") . '【' . $adminname . '】' . $note;
        if ($storerow['note']) {
            $msg = $msg . '<br>' . $storerow['note'];
        }

        $result = StoreApply::where('id', '=', $id)->update(['note' => $msg]);

        return $this->ajaxReturn(0, '备注成功', null);
    }

    /*
     * 本店客户
     * author xfwed
     * date 2019.11.27
     */

//    public function storeCtmList() {
//        $rule = [
//            'store_id' => 'require',
//            'staff_id' => 'require',
//            'type' => 'require',
//            'perPage' => 'integer|egt:1',
//            'page' => 'integer|egt:1',
//        ];
//        $msg = [
//            'store_id.require' => '店铺id必须',
//            'type.require' => '分类必须',
//            'staff_id.require' => '美容师id必须',
//            'perPage.integer' => '每页数量为数字',
//            'perPage.egt' => '每页数量最小为1',
//            'page.integer' => '当前页数为数字',
//            'page.egt' => '当前页数最小为1',
//        ];
//
//        $all = input('param.');
//
//        $validate = new Validate($rule, $msg);
//        if (!$validate->check($all)) {
//            $error = $validate->getError();
//
//            return $this->ajaxReturn(1, $error, null);
//        }
//
//        $type = $all['type']; //1未消费2新客户3老客户4开通特权5体验特权6粉丝
//        $staff_id = $all['staff_id'];
//        $store_id = $all['store_id'];
//        $perPage = isset($all['perPage']) ? $all['perPage'] : 10;
//        $page = isset($all['page']) ? $all['page'] : 0;
//
//
//        if ($staff_id) {
//            $staff_ids = $staff_id;
//        } else {
//            $staff_ids = StaffBindStore::where('store_id', $store_id)->column('staff_id');
//            $staff_ids = implode(",", $staff_ids);
//        }
//        //列表   1未消费2新客户3老客户4开通特权
//        if ($type == 0) {
//            $allList = StaffCtm::alias('s')
//                    ->join('staff st', 'st.id = s.staff_id', 'left')
//                    ->where('s.staff_id', 'in', $staff_ids)
//                    //->where("(SELECT COUNT(`id`) FROM `ai_order` WHERE `staff_id`in(" . $staff_ids . ") and `ctm_id`=s.ctm_id and `status`=2 and `type`in(1,2,5)) = 0")
//                    ->group('s.ctm_id')
//                    ->field('s.ctm_id,st.staff_name')
//                    ->paginate($perPage);
//
//            $data = $allList;
//        } elseif ($type == 1) {
//            $noExpenseList = StaffCtm::alias('s')
//                    ->join('staff st', 'st.id = s.staff_id', 'left')
//                    ->where('s.staff_id', 'in', $staff_ids)
//                    ->where("(SELECT COUNT(`id`) FROM `ai_order` WHERE `staff_id`in(" . $staff_ids . ") and `ctm_id`=s.ctm_id and `status`=2 and `type`in(1,2,5)) = 0")
//                    ->group('s.ctm_id')
//                    ->field('s.ctm_id,st.staff_name')
//                    ->paginate($perPage);
//
//            $data = $noExpenseList;
//        } elseif ($type == 2) {
//            $allList = Order::alias('o')
//                    ->join('staff st', 'st.id = o.staff_id', 'left')
//                    ->where('o.staff_id', 'in', $staff_ids)
//                    ->where('o.status', 2)
//                    ->where("(SELECT COUNT(`id`) FROM `ai_order` WHERE `staff_id`in(" . $staff_ids . ") and `ctm_id`=o.ctm_id and `status`=2 and `type`in(1,2,5)) = 1")
//                    ->group('o.ctm_id')
//                    ->field('o.id,o.ctm_id,st.staff_name')
//                    ->paginate($perPage);
//
//            $data = $allList;
//        } elseif ($type == 3) {
//            $oldList = Order::alias('o')
//                    ->join('staff st', 'st.id = o.staff_id', 'left')
//                    ->where('o.staff_id', 'in', $staff_ids)
//                    ->where('o.status', 2)
//                    ->where("(SELECT COUNT(`id`) FROM `ai_order` WHERE `staff_id`in(" . $staff_ids . ") and `ctm_id`=o.ctm_id and `status`=2 and `type`in(1,2,5)) > 1")
//                    ->group('o.ctm_id')
//                    ->field('o.id,o.ctm_id,st.staff_name')
//                    ->paginate($perPage);
//
//            $data = $oldList;
//        } elseif ($type == 4) {
//            $specialList = Order::alias('o')
//                    ->join('staff st', 'st.id = o.staff_id', 'left')
//                    ->where('o.staff_id', 'in', $staff_ids)
//                    ->where('o.status', 2)
//                    ->where('o.type', 4)
//                    ->group('o.ctm_id')
//                    ->field('o.id,o.ctm_id,st.staff_name')
//                    ->paginate($perPage);
//            $data = $specialList;
//        } elseif ($type == 5) {
//            $expSpecial = StaffCtm::alias('s')
//                    ->join('staff st', 'st.id = s.staff_id', 'left')
//                    ->join('custom c', 'c.id = s.ctm_id')
//                    ->where('c.vip_status', 3)
//                    ->where('s.staff_id', 'in', $staff_ids)
//                    //->where("(SELECT `type` FROM `ai_ctm_special` WHERE `ctm_id`=s.ctm_id AND `end_time`>'" . date('Y-m-d H:i:s', time()) . "' ORDER BY `add_time` DESC LIMIT 0,1)=2")
//                    ->group('s.ctm_id')
//                    ->field('s.ctm_id,st.staff_name')
//                    ->paginate($perPage);
//
//
//            $data = $expSpecial;
//        } elseif ($type == 6) {
//            $ctm_collect = CtmCollect::alias('co')
//                    ->join('custom c', 'c.id = co.ctm_id', 'left')
//                    ->where('co.pro_id', $store_id)
//                    ->where('co.type', 3)
//                    ->field('co.ctm_id')
//                    ->paginate($perPage);
//
//            foreach ($ctm_collect as $k => $v) {
//                $staffId = StaffCtm::where('ctm_id', $v['ctm_id'])->value('staff_id');
//                $ctm_collect[$k]['staff_name'] = Staff::where('id', $staffId)->value('staff_name');
//            }
//            $data = $ctm_collect;
//        }
//        foreach ($data as $k => $v) {
//            $ctmRow = Custom::where('id', $v['ctm_id'])
//                    ->field('id,custom_phone,custom_name,custom_photo,vip_status,add_time,consume_money')
//                    ->find();
//            $notename = StaffNote::where('staff_id', $staff_id)->where('ctm_id', $ctmRow['id'])->field('note,name')->find();
//            $data[$k]['note'] = $notename['note'];
//            $data[$k]['note_name'] = $notename['name'];
//            if ($notename['name']) {
//                $ctmRow['custom_name'] = $notename['name'];
//            }
//            $data[$k]['custom_phone'] = $ctmRow['custom_phone'];
//            $data[$k]['custom_name'] = $ctmRow['custom_name'];
//            $data[$k]['custom_photo'] = $ctmRow['custom_photo'];
//            $data[$k]['vip_status'] = $ctmRow['vip_status'];
//            $data[$k]['add_time'] = $ctmRow['add_time'];
//            $data[$k]['consume_money'] = $ctmRow['consume_money'];
//            $pay_time = Order::where('ctm_id', $v['ctm_id'])
//                    ->where('status', 2)
//                    ->where('pay_money', '>', 0)
//                    ->order('pay_time desc')
//                    ->value('pay_time');
//            $data[$k]['pay_time'] = $pay_time;
//            $orderNum = Order::where('ctm_id', $v['ctm_id'])
//                    ->where('status', 2)
//                    ->where('pay_money', '>', 0)
//                    ->count();
//            $data[$k]['orderNum'] = $orderNum;
//        }
//        return $this->ajaxReturn(0, '成功', $data);
//    }
    
    /*
     * 本店客户
     * author xfwed
     * date 2020.03.25
     */

    public function storeCtmList() {
        $rule = [
            'store_id' => 'require',
            'staff_id' => 'require',
            'type' => 'require',
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:1',
        ];
        $msg = [
            'store_id.require' => '店铺id必须',
            'type.require' => '分类必须',
            'staff_id.require' => '美容师id必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '当前页数为数字',
            'page.egt' => '当前页数最小为1',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }

        $type = $all['type']; //0全部1访客2未预约3新客户4老客户5开通特权6体验特权7开通i美优优8收藏本店
        $specialType = input('param.specialType');//51本店开通  52逆行者活动  53小店转介绍
        $staff_id = $all['staff_id'];
        $store_id = $all['store_id'];
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;
        if ($page == 0) {
            $page = 1;
        }
        $offset = ($page - 1) * $perPage;

        if ($staff_id) {
          if($staff_id == -1){//逆行者活动
              $a = "(SELECT COUNT(`id`) FROM `ai_medical_address` WHERE `ctm_id`= s.ctm_id) > 0";
              $a7 = "(SELECT COUNT(`id`) FROM `ai_medical_address` WHERE `ctm_id`= s.id) > 0";
              $o = "(SELECT COUNT(`id`) FROM `ai_medical_address` WHERE `ctm_id`= o.ctm_id) > 0";
          }elseif ($staff_id == -2) {//店铺分享
              $where['s.staff_id'] = 0;
              $orderwhere['o.staff_id'] = 0;
          }  else {
              $where['s.staff_id'] = $staff_id;
              $orderwhere['o.staff_id'] = $staff_id;
          }  
        } 
        $orderwhere = isset($orderwhere)?$orderwhere:[];
        $a = isset($a) ? $a : '';
        $a7 = isset($a7) ? $a7 : '';
        $o = isset($o) ? $o : '';
        $where['s.store_id'] = $store_id;
        //列表   1未消费2新客户3老客户4开通特权5体验特权
        if ($type == 0) {
            $allList = StoreCtm::alias('s')
                ->join('staff st', 'st.id = s.staff_id', 'left')
                ->where($where)
                ->where($a)
                //->where("(SELECT COUNT(`id`) FROM `ai_order` WHERE `staff_id`in(" . $staff_ids . ") and `ctm_id`=s.ctm_id and `status`=2 and `type`in(1,2,5)) = 0")
                ->group('s.ctm_id')
                ->order('s.add_time desc')
                ->field('s.ctm_id,st.staff_name,st.staff_on')
                ->paginate($perPage);
            foreach ($allList as $k => $v) {
                $ctmRow = Custom::where('id', $v['ctm_id'])
                        ->field('id,source,custom_phone,custom_name,custom_photo,vip_status,is_smallshop,source_type,source_id')
                        ->find();
                $notename = StaffNote::where('staff_id', $staff_id)->where('ctm_id', $ctmRow['id'])->field('note,name')->find();
                $allList[$k]['note'] = $notename['note'];
                $allList[$k]['note_name'] = $notename['name'];
                if ($notename['name']) {
                    $ctmRow['custom_name'] = $notename['name'];
                }
                //查询用户开通特权时间
                if ($ctmRow['vip_status'] == 2 || $ctmRow['vip_status'] == 3) {
                    $specialTime = CtmSpecial::where('ctm_id', $ctmRow['id'])->order('id asc')->find();
                    $allList[$k]['specialTime'] = $specialTime['add_time'];
                    if($specialTime['type'] == 3){
                        $ctmRow['vip_status'] = 4;//4逆行者特权 5i美优优特权 
                    }  else {
                        $specialOrder = Order::alias('o')
                            ->where('o.ctm_id', '=', $ctmRow['id'])
                            ->where('o.status', 2)
                            ->where('o.type', 4)
                            ->where('o.mini_shop_id','<>',0)
                            ->group('ctm_id')
                            ->count();
                        if($specialOrder > 0){
                            $ctmRow['vip_status'] = 5;//4逆行者特权 5i美优优特权 
                        }
                    }
                    if($ctmRow['source'] == 1){
                        $ctmRow['vip_status'] = 6;//4逆行者特权 5i美优优特权 6转入客户特权
                    }
                } else {
                    $allList[$k]['specialTime'] = NULL;
                }
                //查询用户是否为逆行者
                $medicalData = MedicalAddress::where('ctm_id',$ctmRow['id'])->count();
                if($medicalData > 0){
                    $is_medical = 1;
                }  else {
                    $is_medical = 2;
                }
                $allList[$k]['is_medical'] = $is_medical;
                $allList[$k]['is_smallshop'] = $ctmRow['is_smallshop'];
                
                $allList[$k]['custom_phone'] = $ctmRow['custom_phone'];
                $allList[$k]['custom_name'] = $ctmRow['custom_name'];
                $allList[$k]['custom_photo'] = $ctmRow['custom_photo'];
                $allList[$k]['vip_status'] = $ctmRow['vip_status'];
                $allList[$k]['source_type'] = $ctmRow['source_type'];
                $allList[$k]['source_id'] = $ctmRow['source_id'];
                $pay_time = Order::where('ctm_id', $v['ctm_id'])
                        ->where('status', 2)
                        //->where('pay_money', '>', 0)
                        ->where('store_id',$store_id)
                        ->order('pay_time desc')
                        ->value('pay_time');
                $allList[$k]['pay_time'] = $pay_time;
            }
            $data = $allList;
        } elseif ($type == 1) {
            $noExpenseList = StoreCtm::alias('s')
                    ->join('staff st', 'st.id = s.staff_id', 'left')
                    ->where($where)
                    ->where($a)
                    ->where("(SELECT COUNT(`id`) FROM `ai_order` WHERE `store_id`=" . $store_id . " and `ctm_id`=s.ctm_id and `status`=2 and `type`in(1,2,5)) = 0")
                    ->group('s.ctm_id')
                    ->order('s.add_time desc')
                    ->field('s.ctm_id,st.staff_name,st.staff_on,s.add_time')
                    ->paginate($perPage);
            foreach ($noExpenseList as $k => $v) {
                $ctmRow = Custom::where('id', $v['ctm_id'])
                        ->field('id,source,custom_phone,custom_name,custom_photo,vip_status,is_smallshop,source_type,source_id')
                        ->find();
                $notename = StaffNote::where('staff_id', $staff_id)->where('ctm_id', $ctmRow['id'])->field('note,name')->find();
                $noExpenseList[$k]['note'] = $notename['note'];
                $noExpenseList[$k]['note_name'] = $notename['name'];
                if ($notename['name']) {
                    $ctmRow['custom_name'] = $notename['name'];
                }
                //查询用户开通特权时间
                if ($ctmRow['vip_status'] == 2 || $ctmRow['vip_status'] == 3) {
                    $specialTime = CtmSpecial::where('ctm_id', $ctmRow['id'])->order('id asc')->find();
                    $noExpenseList[$k]['specialTime'] = $specialTime['add_time'];
                    if($specialTime['type'] == 3){
                        $ctmRow['vip_status'] = 4;//4逆行者特权 5i美优优特权 
                    }  else {
                        $specialOrder = Order::alias('o')
                            ->where('o.ctm_id', '=', $ctmRow['id'])
                            ->where('o.status', 2)
                            ->where('o.type', 4)
                            ->where('o.mini_shop_id','<>',0)
                            ->group('ctm_id')
                            ->count();
                        if($specialOrder > 0){
                            $ctmRow['vip_status'] = 5;//4逆行者特权 5i美优优特权 
                        }
                    }
                    if($ctmRow['source'] == 1){
                        $ctmRow['vip_status'] = 6;//4逆行者特权 5i美优优特权 6转入客户特权
                    }
                } else {
                    $noExpenseList[$k]['specialTime'] = NULL;
                }
                //查询用户是否为逆行者
                $medicalData = MedicalAddress::where('ctm_id',$ctmRow['id'])->count();
                if($medicalData > 0){
                    $is_medical = 1;
                }  else {
                    $is_medical = 2;
                }
                $noExpenseList[$k]['is_medical'] = $is_medical;
                $noExpenseList[$k]['is_smallshop'] = $ctmRow['is_smallshop'];
                $noExpenseList[$k]['custom_phone'] = $ctmRow['custom_phone'];
                $noExpenseList[$k]['custom_name'] = $ctmRow['custom_name'];
                $noExpenseList[$k]['custom_photo'] = $ctmRow['custom_photo'];
                $noExpenseList[$k]['vip_status'] = $ctmRow['vip_status'];
                $noExpenseList[$k]['source_type'] = $ctmRow['source_type'];
                $noExpenseList[$k]['source_id'] = $ctmRow['source_id'];
                $noExpenseList[$k]['pay_time'] = null;
            }
            $data = $noExpenseList;
        }elseif ($type == 2) {
            $allList = StoreCtm::alias('s')
                    ->join('staff st', 'st.id = s.staff_id', 'left')
                    ->where($where)
                    ->where($a)
                    ->where("(SELECT COUNT(`id`) FROM `ai_order` WHERE `store_id`=" . $store_id . " and `ctm_id`=s.ctm_id and `status`=2 and `type`in(1,2,5)) > 0")
                    ->where("(SELECT COUNT(`id`) FROM `ai_yuyue` WHERE `store_id`=".$store_id." and `status`>1 and `ctm_id`=s.ctm_id)=0")
                    ->group('s.ctm_id')
                    ->order('s.add_time desc')
                    ->field('s.ctm_id,st.staff_name,st.staff_on,s.add_time')
                    ->paginate($perPage);
            foreach ($allList as $k => $v) {
                $ctmRow = Custom::where('id', $v['ctm_id'])
                        ->field('id,source,custom_phone,custom_name,custom_photo,vip_status,is_smallshop,source_type,source_id')
                        ->find();
                $notename = StaffNote::where('staff_id', $staff_id)->where('ctm_id', $ctmRow['id'])->field('note,name')->find();
                $allList[$k]['note'] = $notename['note'];
                $allList[$k]['note_name'] = $notename['name'];
                if ($notename['name']) {
                    $ctmRow['custom_name'] = $notename['name'];
                }

                //查询用户开通特权时间
                if ($ctmRow['vip_status'] == 2 || $ctmRow['vip_status'] == 3) {
                    $specialTime = CtmSpecial::where('ctm_id', $ctmRow['id'])->order('id asc')->find();
                    $allList[$k]['specialTime'] = $specialTime['add_time'];
                    if($specialTime['type'] == 3){
                        $ctmRow['vip_status'] = 4;//4逆行者特权 5i美优优特权 
                    }  else {
                        $specialOrder = Order::alias('o')
                            ->where('o.ctm_id', '=', $ctmRow['id'])
                            ->where('o.status', 2)
                            ->where('o.type', 4)
                            ->where('o.mini_shop_id','<>',0)
                            ->group('ctm_id')
                            ->count();
                        if($specialOrder > 0){
                            $ctmRow['vip_status'] = 5;//4逆行者特权 5i美优优特权 
                        }
                    }
                    if($ctmRow['source'] == 1){
                        $ctmRow['vip_status'] = 6;//4逆行者特权 5i美优优特权 6转入客户特权
                    }
                } else {
                    $allList[$k]['specialTime'] = NULL;
                }
                //查询用户是否为逆行者
                $medicalData = MedicalAddress::where('ctm_id',$ctmRow['id'])->count();
                if($medicalData > 0){
                    $is_medical = 1;
                }  else {
                    $is_medical = 2;
                }
                $allList[$k]['is_medical'] = $is_medical;
                $allList[$k]['is_smallshop'] = $ctmRow['is_smallshop'];
                
                $allList[$k]['custom_phone'] = $ctmRow['custom_phone'];
                $allList[$k]['custom_name'] = $ctmRow['custom_name'];
                $allList[$k]['custom_photo'] = $ctmRow['custom_photo'];
                $allList[$k]['vip_status'] = $ctmRow['vip_status'];
                $allList[$k]['source_type'] = $ctmRow['source_type'];
                $allList[$k]['source_id'] = $ctmRow['source_id'];
                $pay_time = Order::where('ctm_id', $v['ctm_id'])
                        ->where('status', 2)
                        //->where('pay_money', '>', 0)
                        ->where('store_id',$store_id)
                        ->order('pay_time desc')
                        ->value('pay_time');
                $allList[$k]['pay_time'] = $pay_time;
            }
            $data = $allList;
        } elseif ($type == 3) {
            $allList = Order::alias('o')
                    ->join('staff st', 'st.id = o.staff_id', 'left')
                    ->where('o.store_id', '=', $store_id)
                    ->where('o.status', 2)
                    ->where($orderwhere)
                    ->where($o)
                    ->where("(SELECT COUNT(`id`) FROM `ai_order` WHERE `store_id`=" . $store_id . " and `ctm_id`=o.ctm_id and `status`=2 and `type`in(1,2,5)) = 1")
                    ->group('o.ctm_id')
                    ->order('o.pay_time desc')
                    ->field('o.id,o.ctm_id,st.staff_name,st.staff_on')
                    ->paginate($perPage);
            foreach ($allList as $k => $v) {
                $ctmRow = Custom::where('id', $v['ctm_id'])
                        ->field('id,source,custom_phone,custom_name,custom_photo,vip_status,is_smallshop,source_type,source_id')
                        ->find();
                $notename = StaffNote::where('staff_id', $staff_id)->where('ctm_id', $ctmRow['id'])->field('note,name')->find();
                $allList[$k]['note'] = $notename['note'];
                $allList[$k]['note_name'] = $notename['name'];
                if ($notename['name']) {
                    $ctmRow['custom_name'] = $notename['name'];
                }

                //查询用户开通特权时间
                if ($ctmRow['vip_status'] == 2 || $ctmRow['vip_status'] == 3) {
                    $specialTime = CtmSpecial::where('ctm_id', $ctmRow['id'])->order('id asc')->find();
                    $allList[$k]['specialTime'] = $specialTime['add_time'];
                    if($specialTime['type'] == 3){
                        $ctmRow['vip_status'] = 4;//4逆行者特权 5i美优优特权 
                    }  else {
                        $specialOrder = Order::alias('o')
                            ->where('o.ctm_id', '=', $ctmRow['id'])
                            ->where('o.status', 2)
                            ->where('o.type', 4)
                            ->where('o.mini_shop_id','<>',0)
                            ->group('ctm_id')
                            ->count();
                        if($specialOrder > 0){
                            $ctmRow['vip_status'] = 5;//4逆行者特权 5i美优优特权 
                        }
                    }
                    if($ctmRow['source'] == 1){
                        $ctmRow['vip_status'] = 6;//4逆行者特权 5i美优优特权 6转入客户特权
                    }
                } else {
                    $allList[$k]['specialTime'] = NULL;
                }
                //查询用户是否为逆行者
                $medicalData = MedicalAddress::where('ctm_id',$ctmRow['id'])->count();
                if($medicalData > 0){
                    $is_medical = 1;
                }  else {
                    $is_medical = 2;
                }
                $allList[$k]['is_medical'] = $is_medical;
                $allList[$k]['is_smallshop'] = $ctmRow['is_smallshop'];
                
                $allList[$k]['custom_phone'] = $ctmRow['custom_phone'];
                $allList[$k]['custom_name'] = $ctmRow['custom_name'];
                $allList[$k]['custom_photo'] = $ctmRow['custom_photo'];
                $allList[$k]['vip_status'] = $ctmRow['vip_status'];
                $allList[$k]['source_type'] = $ctmRow['source_type'];
                $allList[$k]['source_id'] = $ctmRow['source_id'];
                $pay_time = Order::where('ctm_id', $v['ctm_id'])
                        ->where('status', 2)
                        ->where('type','in','1,2,5')
                        //->where('pay_money', '>', 0)
                        ->where('store_id',$store_id)
                        ->order('pay_time desc')
                        ->value('pay_time');
                $allList[$k]['pay_time'] = $pay_time;
            }
            $data = $allList;
        } elseif ($type == 4) {
            $oldList = Order::alias('o')
                    ->join('staff st', 'st.id = o.staff_id', 'left')
                    ->where('o.store_id', '=', $store_id)
                    ->where('o.status', 2)
                    ->where($orderwhere)
                    ->where($o)
                    ->where("(SELECT COUNT(`id`) FROM `ai_order` WHERE `store_id`=" . $store_id . " and `ctm_id`=o.ctm_id and `status`=2 and `type`in(1,2,5)) > 1")
                    ->group('o.ctm_id')
                    ->order('o.pay_time desc')
                    ->field('o.id,o.ctm_id,o.pay_time,st.staff_name,st.staff_on')
                    ->paginate($perPage);
            foreach ($oldList as $k => $v) {
                $ctmRow = Custom::where('id', $v['ctm_id'])
                        ->field('id,source,custom_phone,custom_name,custom_photo,vip_status,is_smallshop,source_type,source_id')
                        ->find();
                $notename = StaffNote::where('staff_id', $staff_id)->where('ctm_id', $ctmRow['id'])->field('note,name')->find();
                $oldList[$k]['note'] = $notename['note'];
                $oldList[$k]['note_name'] = $notename['name'];
                if ($notename['name']) {
                    $ctmRow['custom_name'] = $notename['name'];
                }
                //查询用户开通特权时间
                if ($ctmRow['vip_status'] == 2 || $ctmRow['vip_status'] == 3) {
                    $specialTime = CtmSpecial::where('ctm_id', $ctmRow['id'])->order('id asc')->find();
                    $oldList[$k]['specialTime'] = $specialTime['add_time'];
                    if($specialTime['type'] == 3){
                        $ctmRow['vip_status'] = 4;//4逆行者特权 5i美优优特权 
                    }  else {
                        $specialOrder = Order::alias('o')
                            ->where('o.ctm_id', '=', $ctmRow['id'])
                            ->where('o.status', 2)
                            ->where('o.type', 4)
                            ->where('o.mini_shop_id','<>',0)
                            ->group('ctm_id')
                            ->count();
                        if($specialOrder > 0){
                            $ctmRow['vip_status'] = 5;//4逆行者特权 5i美优优特权 
                        }
                    }
                    if($ctmRow['source'] == 1){
                        $ctmRow['vip_status'] = 6;//4逆行者特权 5i美优优特权 6转入客户特权
                    }
                } else {
                    $oldList[$k]['specialTime'] = NULL;
                }
                //查询用户是否为逆行者
                $medicalData = MedicalAddress::where('ctm_id',$ctmRow['id'])->count();
                if($medicalData > 0){
                    $is_medical = 1;
                }  else {
                    $is_medical = 2;
                }
                $oldList[$k]['is_medical'] = $is_medical;
                $oldList[$k]['is_smallshop'] = $ctmRow['is_smallshop'];
                
                $oldList[$k]['custom_phone'] = $ctmRow['custom_phone'];
                $oldList[$k]['custom_name'] = $ctmRow['custom_name'];
                $oldList[$k]['custom_photo'] = $ctmRow['custom_photo'];
                $oldList[$k]['vip_status'] = $ctmRow['vip_status'];
                $oldList[$k]['source_type'] = $ctmRow['source_type'];
                $oldList[$k]['source_id'] = $ctmRow['source_id'];
//                $pay_time = Order::where('ctm_id', $v['ctm_id'])
//                        ->where('status', 2)
//                        ->where('type','in','1,2,5')
//                        //->where('pay_money', '>', 0)
//                        ->where('store_id',$store_id)
//                        ->order('pay_time desc')
//                        ->value('pay_time');
//                $oldList[$k]['pay_time'] = $pay_time;
            }
            $data = $oldList;
        } elseif ($type == 5) {
            if($specialType == 51){
               $specialList = Order::alias('o')
                    ->join('staff st', 'st.id = o.staff_id', 'left')
                    ->where('o.store_id', '=', $store_id)
                    ->where('o.status', 2)
                    ->where('o.type', 4)
                    ->where($orderwhere)
                    ->where($o)
                    ->where('o.mini_shop_id',0)
                    ->group('o.ctm_id')
                    ->order('o.pay_time desc')
                    ->field('o.id,o.ctm_id,st.staff_name,st.staff_on')
                   ->paginate($perPage);
            }elseif ($specialType == 52) {
                $specialList = StoreCtm::alias('s')
                    ->join('custom c', 'c.id = s.ctm_id','left')
                    ->join('ctm_special cs','cs.ctm_id=s.ctm_id','left')
                    ->join('staff st', 'st.id = s.staff_id', 'left')
                    ->where('c.vip_status', 2)
                    ->where('cs.type',3)
                    ->where($where)
                    ->where($a)
                    ->field('s.ctm_id,st.staff_name,st.staff_on')
                    ->group('s.ctm_id')
                    ->order('s.add_time desc')
                    ->paginate($perPage);
            }elseif ($specialType == 53) {
                $specialList = Order::alias('o')
                    ->join('staff st', 'st.id = o.staff_id', 'left')
                    ->where('o.store_id', '=', $store_id)
                    ->where('o.status', 2)
                    ->where('o.type', 4)
                    ->where($orderwhere)
                    ->where($o)
                    ->where('o.mini_shop_id','<>',0)
                    ->group('o.ctm_id')
                    ->order('o.pay_time desc')
                    ->field('o.id,o.ctm_id,st.staff_name,st.staff_on')
                    ->paginate($perPage);
            }elseif ($specialType == 54) {
                $specialList = StoreCtm::alias('s')
                    ->join('custom c', 'c.id = s.ctm_id','left')
                    ->join('staff st', 'st.id = s.staff_id', 'left')
                    ->where('c.vip_status', 2)
                    ->where('c.source',1)
                    ->where($where)
                    ->field('s.ctm_id,st.staff_name,st.staff_on')
                    ->group('s.ctm_id')
                    ->order('s.add_time desc')
                    ->paginate($perPage);
            }
            
            foreach ($specialList as $k => $v) {
                $ctmRow = Custom::where('id', $v['ctm_id'])
                        ->field('id,source,custom_phone,custom_name,custom_photo,vip_status,is_smallshop,source_type,source_id')
                        ->find();
                $notename = StaffNote::where('staff_id', $staff_id)->where('ctm_id', $ctmRow['id'])->field('note,name')->find();
                $specialList[$k]['note'] = $notename['note'];
                $specialList[$k]['note_name'] = $notename['name'];
                if ($notename['name']) {
                    $ctmRow['custom_name'] = $notename['name'];
                }
               //查询用户开通特权时间
                if ($ctmRow['vip_status'] == 2 || $ctmRow['vip_status'] == 3) {
                    $specialTime = CtmSpecial::where('ctm_id', $ctmRow['id'])->order('id asc')->find();
                    $specialList[$k]['specialTime'] = $specialTime['add_time'];
                    if($specialTime['type'] == 3){
                        $ctmRow['vip_status'] = 4;//4逆行者特权 5i美优优特权 
                    }  else {
                        $specialOrder = Order::alias('o')
                            ->where('o.ctm_id', '=', $ctmRow['id'])
                            ->where('o.status', 2)
                            ->where('o.type', 4)
                            ->where('o.mini_shop_id','<>',0)
                            ->group('ctm_id')
                            ->count();
                        if($specialOrder > 0){
                            $ctmRow['vip_status'] = 5;//4逆行者特权 5i美优优特权 
                        }
                    }
                    if($ctmRow['source'] == 1){
                        $ctmRow['vip_status'] = 6;//4逆行者特权 5i美优优特权 6转入客户特权
                    }
                } else {
                    $specialList[$k]['specialTime'] = NULL;
                }
                //查询用户是否为逆行者
                $medicalData = MedicalAddress::where('ctm_id',$ctmRow['id'])->count();
                if($medicalData > 0){
                    $is_medical = 1;
                }  else {
                    $is_medical = 2;
                }
                $specialList[$k]['is_medical'] = $is_medical;
                $specialList[$k]['is_smallshop'] = $ctmRow['is_smallshop'];
                
                $specialList[$k]['custom_phone'] = $ctmRow['custom_phone'];
                $specialList[$k]['custom_name'] = $ctmRow['custom_name'];
                $specialList[$k]['custom_photo'] = $ctmRow['custom_photo'];
                $specialList[$k]['vip_status'] = $ctmRow['vip_status'];
                $specialList[$k]['source_type'] = $ctmRow['source_type'];
                $specialList[$k]['source_id'] = $ctmRow['source_id'];
                $pay_time = Order::where('ctm_id', $v['ctm_id'])
                        ->where('status', 2)
                        //->where('pay_money', '>', 0)
                        ->where('store_id',$store_id)
                        ->order('pay_time desc')
                        ->value('pay_time');
                $specialList[$k]['pay_time'] = $pay_time;
            }

            $data = $specialList;
        } elseif ($type == 6) {
            $expSpecial = StoreCtm::alias('s')
                    ->join('staff st', 'st.id = s.staff_id', 'left')
                    ->join('custom c', 'c.id = s.ctm_id')
                    ->join('ctm_special cs','cs.ctm_id = c.id')
                    ->where('c.vip_status', 3)
                    ->where($where)
                    ->where($a)
                    //->where("(SELECT `type` FROM `ai_ctm_special` WHERE `ctm_id`=s.ctm_id AND `end_time`>'" . date('Y-m-d H:i:s', time()) . "' ORDER BY `add_time` DESC LIMIT 0,1)=2")
                    ->group('s.ctm_id')
                    ->order('cs.add_time desc')
                    ->field('s.ctm_id,st.staff_name,st.staff_on')
                    ->paginate($perPage);

            foreach ($expSpecial as $k => $v) {
                $ctmRow = Custom::where('id', $v['ctm_id'])
                        ->field('id,source,custom_phone,custom_name,custom_photo,vip_status,is_smallshop,source_type,source_id')
                        ->find();
                $notename = StaffNote::where('staff_id', $staff_id)->where('ctm_id', $ctmRow['id'])->field('note,name')->find();
                $expSpecial[$k]['note'] = $notename['note'];
                $expSpecial[$k]['note_name'] = $notename['name'];
                if ($notename['name']) {
                    $ctmRow['custom_name'] = $notename['name'];
                }
                //查询用户开通特权时间
                if ($ctmRow['vip_status'] == 2 || $ctmRow['vip_status'] == 3) {
                    $specialTime = CtmSpecial::where('ctm_id', $ctmRow['id'])->order('id asc')->find();
                    $expSpecial[$k]['specialTime'] = $specialTime['add_time'];
                    if($specialTime['type'] == 3){
                        $ctmRow['vip_status'] = 4;//4逆行者特权 5i美优优特权 
                    }  else {
                        $specialOrder = Order::alias('o')
                            ->where('o.ctm_id', '=', $ctmRow['id'])
                            ->where('o.status', 2)
                            ->where('o.type', 4)
                            ->where('o.mini_shop_id','<>',0)
                            ->group('ctm_id')
                            ->count();
                        if($specialOrder > 0){
                            $ctmRow['vip_status'] = 5;//4逆行者特权 5i美优优特权 
                        }
                    }
                    if($ctmRow['source'] == 1){
                        $ctmRow['vip_status'] = 6;//4逆行者特权 5i美优优特权 6转入客户特权
                    }
                } else {
                    $expSpecial[$k]['specialTime'] = NULL;
                }
                //查询用户是否为逆行者
                $medicalData = MedicalAddress::where('ctm_id',$ctmRow['id'])->count();
                if($medicalData > 0){
                    $is_medical = 1;
                }  else {
                    $is_medical = 2;
                }
                $expSpecial[$k]['is_medical'] = $is_medical;
                $expSpecial[$k]['is_smallshop'] = $ctmRow['is_smallshop'];
                
                $expSpecial[$k]['expspecial_time'] = $specialTime;
                $expSpecial[$k]['custom_phone'] = $ctmRow['custom_phone'];
                $expSpecial[$k]['custom_name'] = $ctmRow['custom_name'];
                $expSpecial[$k]['custom_photo'] = $ctmRow['custom_photo'];
                $expSpecial[$k]['vip_status'] = $ctmRow['vip_status'];
                $expSpecial[$k]['source_type'] = $ctmRow['source_type'];
                $expSpecial[$k]['source_id'] = $ctmRow['source_id'];
                $expSpecial[$k]['pay_time'] = null;
            }
            $data = $expSpecial;
        }elseif ($type == 7) {
            $smallshop = Custom::alias('s')
                ->where('s.smallshop_storeid',$store_id)
                ->where('s.status', 2)
                ->where($a7)
                ->order('s.smallshop_time desc')
                ->field('s.id ctm_id,s.smallshop_time')
                ->paginate($perPage);

            foreach ($smallshop as $k => $v) {
                $staffId = StaffCtm::where('ctm_id', $v['ctm_id'])->value('staff_id');
                $smallshop[$k]['staff_name'] = Staff::where('id', $staffId)->value('staff_name');
                $smallshop[$k]['staff_on'] = Staff::where('id', $staffId)->value('staff_on');
                $ctmRow = Custom::where('id', $v['ctm_id'])
                        ->field('id,source,custom_phone,custom_name,custom_photo,vip_status,is_smallshop,source_type,source_id')
                        ->find();
                $notename = StaffNote::where('staff_id', $staff_id)->where('ctm_id', $ctmRow['id'])->field('note,name')->find();
                $smallshop[$k]['note'] = $notename['note'];
                $smallshop[$k]['note_name'] = $notename['name'];
                if ($notename['name']) {
                    $ctmRow['custom_name'] = $notename['name'];
                }
                //查询用户开通特权时间
                if ($ctmRow['vip_status'] == 2 || $ctmRow['vip_status'] == 3) {
                    $specialTime = CtmSpecial::where('ctm_id', $ctmRow['id'])->order('id asc')->find();
                    $smallshop[$k]['specialTime'] = $specialTime['add_time'];
                    if($specialTime['type'] == 3){
                        $ctmRow['vip_status'] = 4;//4逆行者特权 5i美优优特权 
                    }  else {
                        $specialOrder = Order::alias('o')
                            ->where('o.ctm_id', '=', $ctmRow['id'])
                            ->where('o.status', 2)
                            ->where('o.type', 4)
                            ->where('o.mini_shop_id','<>',0)
                            ->group('ctm_id')
                            ->count();
                        if($specialOrder > 0){
                            $ctmRow['vip_status'] = 5;//4逆行者特权 5i美优优特权 
                        }
                    }
                    if($ctmRow['source'] == 1){
                        $ctmRow['vip_status'] = 6;//4逆行者特权 5i美优优特权 6转入客户特权
                    }
                } else {
                    $smallshop[$k]['specialTime'] = NULL;
                }
                //查询用户是否为逆行者
                $medicalData = MedicalAddress::where('ctm_id',$ctmRow['id'])->count();
                if($medicalData > 0){
                    $is_medical = 1;
                }  else {
                    $is_medical = 2;
                }
                $smallshop[$k]['is_medical'] = $is_medical;
                $smallshop[$k]['is_smallshop'] = $ctmRow['is_smallshop'];
                
                $smallshop[$k]['custom_phone'] = $ctmRow['custom_phone'];
                $smallshop[$k]['custom_name'] = $ctmRow['custom_name'];
                $smallshop[$k]['custom_photo'] = $ctmRow['custom_photo'];
                $smallshop[$k]['vip_status'] = $ctmRow['vip_status'];
                $smallshop[$k]['source_type'] = $ctmRow['source_type'];
                $smallshop[$k]['source_id'] = $ctmRow['source_id'];
                $smallshop[$k]['pay_time'] = null;
            }
            $data = $smallshop;
        } elseif ($type == 8) {
            $ctm_collect = CtmCollect::alias('co')
                    ->join('custom s', 's.id = co.ctm_id', 'left')
                    ->where('co.pro_id', $store_id)
                    ->where('co.type', 3)
                    ->where($a7)
                    ->order('co.add_time desc')
                    ->field('co.ctm_id,co.add_time collect_time')
                    ->paginate($perPage);

            foreach ($ctm_collect as $k => $v) {
                $staffId = StaffCtm::where('ctm_id', $v['ctm_id'])->value('staff_id');
                $ctm_collect[$k]['staff_name'] = Staff::where('id', $staffId)->value('staff_name');
                $ctm_collect[$k]['staff_on'] = Staff::where('id', $staffId)->value('staff_on');
                $ctmRow = Custom::where('id', $v['ctm_id'])
                        ->field('id,source,custom_phone,custom_name,custom_photo,vip_status,is_smallshop,source_type,source_id')
                        ->find();
                $notename = StaffNote::where('staff_id', $staff_id)->where('ctm_id', $ctmRow['id'])->field('note,name')->find();
                $ctm_collect[$k]['note'] = $notename['note'];
                $ctm_collect[$k]['note_name'] = $notename['name'];
                if ($notename['name']) {
                    $ctmRow['custom_name'] = $notename['name'];
                }
                //查询用户开通特权时间
                if ($ctmRow['vip_status'] == 2 || $ctmRow['vip_status'] == 3) {
                    $specialTime = CtmSpecial::where('ctm_id', $ctmRow['id'])->order('id asc')->find();
                    $ctm_collect[$k]['specialTime'] = $specialTime['add_time'];
                    if($specialTime['type'] == 3){
                        $ctmRow['vip_status'] = 4;//4逆行者特权 5i美优优特权 
                    }  else {
                        $specialOrder = Order::alias('o')
                            ->where('o.ctm_id', '=', $ctmRow['id'])
                            ->where('o.status', 2)
                            ->where('o.type', 4)
                            ->where('o.mini_shop_id','<>',0)
                            ->group('ctm_id')
                            ->count();
                        if($specialOrder > 0){
                            $ctmRow['vip_status'] = 5;//4逆行者特权 5i美优优特权 
                        }
                    }
                    if($ctmRow['source'] == 1){
                        $ctmRow['vip_status'] = 6;//4逆行者特权 5i美优优特权 6转入客户特权
                    }
                } else {
                    $ctm_collect[$k]['specialTime'] = NULL;
                }
                //查询用户是否为逆行者
                $medicalData = MedicalAddress::where('ctm_id',$ctmRow['id'])->count();
                if($medicalData > 0){
                    $is_medical = 1;
                }  else {
                    $is_medical = 2;
                }
                $ctm_collect[$k]['is_medical'] = $is_medical;
                $ctm_collect[$k]['is_smallshop'] = $ctmRow['is_smallshop'];
                
                $ctm_collect[$k]['custom_phone'] = $ctmRow['custom_phone'];
                $ctm_collect[$k]['custom_name'] = $ctmRow['custom_name'];
                $ctm_collect[$k]['custom_photo'] = $ctmRow['custom_photo'];
                $ctm_collect[$k]['vip_status'] = $ctmRow['vip_status'];
                $ctm_collect[$k]['source_type'] = $ctmRow['source_type'];
                $ctm_collect[$k]['source_id'] = $ctmRow['source_id'];
                $ctm_collect[$k]['pay_time'] = null;
            }
            $data = $ctm_collect;
        }
        foreach ($data as $k => $v){
            if($v['source_type'] == 0){
                $sourceName = '';
            }elseif ($v['source_type'] == 1) {
                $sourceName = '平台引流';
            }elseif ($v['source_type'] == 2) {
                $staffName = Staff::where('id',$v['source_id'])->value('staff_name');
                $sourceName = $staffName;
            }elseif ($v['source_type'] == 3) {
                $StoreRow = Store::where('id',$v['source_id'])->field('store_name,city')->find();
                $cityName = ProvCityArea::where('id',$StoreRow['city'])->value('name');
                $sourceName = $cityName.'的'.$StoreRow['store_name'];
            }elseif ($v['source_type'] == 4) {
                $sourceName = '小店转介绍';
            }
            $data[$k]['sourceName'] = $sourceName;
        }
        return Utils::ajaxReturn(0, '成功', $data);
    }

    /*
     * 店铺美容师解绑
     * author xfwed
     * date 2019-12-18
     */

    public function unbindStaff() {
        $staff_id = input('param.staff_id');
        $store_id = input('param.store_id');
        $save = StaffBindStore::where('staff_id', $staff_id)
                ->where('store_id', $store_id)
                ->delete();
        //调振阳接口 发推送
        $ApiPath = config('appconfig.ApiPath8890');
        $result = Utils::curlPost1($ApiPath . 'staff/bindStore/' . $staff_id.'/'.$store_id.'/0');
        $result = json_decode($result, TRUE);
        if($save && $result['code']==0){
            return $this->ajaxReturn(0, '解绑成功', NULL);
        }
    }
    
    /*
     * 设置店铺是否营业
     * author xfwed 
     * date 2020.07.02
     */

    public function storeIsOpen() {
        $store_id = input('param.store_id');
        $is_open = input('param.is_open');//1是2否营业
        $decorate_start = input('param.decorate_start');//装修开始日期	
        $decorate_end = input('param.decorate_end');//装修结束日期	
        if($is_open!=1 && $is_open!=2){
            return $this->ajaxReturn(3, '参数有误', null);
        }
        
        $row = Store::where('id',$store_id)->update([
            'is_open'=>$is_open,
            'decorate_start' => $decorate_start,
            'decorate_end' => $decorate_end,
                ]);
        if($row){
            if($is_open == 1){
            //给店铺开通小店
            $ApiPath8891 = config('appconfig.ApiPath');
            $relust = Utils::curlPost($ApiPath8891 . '/smallshop/storeAndStaffOpenShop/'.$store_id.'/2/0');
            //给店铺用户发送短信
            //发送短信
//            $store_name = Store::where('id',$store_id)->value('store_name');
//            $content = "尊敬的顾客，DAVIDKKM无人美容店-".$store_name."已开业。登录微信小程序【DAVID KKM】，新客专享项目9.9。退订回T";
//            $telephone = StoreCtm::alias('s')
//                    ->join('custom c','c.id = s.ctm_id','left')
//                    ->where('s.store_id',$store_id)
//                    ->group('s.ctm_id')
//                    ->column('c.custom_phone');
//            $telephone = implode(",", $telephone);  
//            //return $this->ajaxReturn(0, '设置成功', $telephone.'------'.$content);
//            $sendResult = Utils::sendSemSms($telephone, $content);
            }
            return $this->ajaxReturn(0, '设置成功', null);
        }  else {
            return $this->ajaxReturn(3, '设置失败', null);
        }
        
    }
    
    /*
     * 设置店铺下架的项目
     * author xfwed 
     * date 2020.07.02
     */

    public function storeSoldOutItem() {
        $store_id = input('param.store_id');
        $item_ids = input('param.item_ids');//需要下架的项目id  多个用逗号隔开
        $overgroup_ids = input('param.overgroup_ids');//需要下架的组合id  多个用逗号隔开
        $miaosha_ids = input('param.miaosha_ids');//需要下架的秒杀id  多个用逗号隔开
        $type = input('param.type');//1修改前回显 2修改
        
        if($type == 1){
            $row = StoreSoldoutitem::where('store_id',$store_id)->find();
            if($row){
                $item_ids = explode(',',$row['item_ids']);
                $soldList = Item::where('status',2)
                        //->where('id','not in',$item_ids)
                        ->where('is_del',1)
                        ->field('id,item_name')
                        ->select();
                $soldOutList = Item::where('status',2)
                        ->where('id','in',$item_ids)
                        ->where('is_del',1)
                        ->field('id,item_name')
                        ->select();
                
                $overgroup_ids = explode(',',$row['overgroup_ids']);
                $soldOvergroupList = Overgroup::where('status',1)
                        //->where('id','not in',$item_ids)
                        ->field('id,name,price')
                        ->select();
                $soldOutOvergroupList = Overgroup::where('status',1)
                        ->where('id','in',$overgroup_ids)
                        ->field('id,name,price')
                        ->select();
                
                $miaosha_ids = explode(',', $row['miaosha_ids']);
                $soldMiaoshaList = Miaosha::where('is_del',1)
                        ->where('start_time','<',date('Y-m-d H:i:s'))
                        ->field('id,name,price')
                        ->select();
                $soldOutMiaoshaList = Miaosha::where('id','in',$miaosha_ids)
                        ->field('id,name,price')
                        ->select();
                
            }  else {
                $soldList = Item::where('status',2)
                        ->where('is_del',1)
                        ->field('id,item_name')
                        ->select();
                $soldOutList = [];
                
                $soldOvergroupList = Overgroup::where('status',1)
                        ->field('id,name,price')
                        ->select();
                $soldOutOvergroupList = [];
                
                $soldMiaoshaList = Miaosha::where('is_del',1)
                        ->where('start_time','<',date('Y-m-d H:i:s'))
                        ->field('id,name,price')
                        ->select();
                $soldOutMiaoshaList = [];
            }
            $data['soldList'] = $soldList;
            $data['soldOutList'] = $soldOutList;
            
            $data['soldOvergroupList'] = $soldOvergroupList;
            $data['soldOutOvergroupList'] = $soldOutOvergroupList;
            
            $data['soldMiaoshaList'] = $soldMiaoshaList;
            $data['soldOutMiaoshaList'] = $soldOutMiaoshaList;
            
            return $this->ajaxReturn(0, '查询成功', $data);
        }  else {
            $row = StoreSoldoutitem::where('store_id',$store_id)->find();
            if($row){//有就是修改
                $save = StoreSoldoutitem::where('id',$row['id'])
                        ->update(['item_ids'=>$item_ids,'overgroup_ids'=>$overgroup_ids,'miaosha_ids'=>$miaosha_ids]);
            }  else {//没有就是新增
                $insertdata['store_id'] = $store_id;
                $insertdata['item_ids'] = $item_ids;
                $insertdata['overgroup_ids'] = $overgroup_ids;
                $insertdata['miaosha_ids'] = $miaosha_ids;
                $insertdata['add_time'] = date('Y-m-d H:i:s');
                $save = StoreSoldoutitem::insert($insertdata);
            }
            if($save){
                return $this->ajaxReturn(0, '设置成功', null);
            }  else {
                return $this->ajaxReturn(3, '设置失败', null);
            }
        }
        
    }
    
    /*
     * 服务人次
     * author xfwed
     * date 2020-08-14
     * @param storeId
     * @param dateType 0.本日 1.本周 2.本月 3.全部 4.自定义
     * */

    public function getServiceCountList() {
        $storeId = input('param.id'); //店铺id
        $perPage = input('param.perPage');
        $page = input('param.page');
        $dateType = input('param.dateType');
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        $ApiPath = config('appconfig.ApiPath8890');
        if($dateType == 4){
            $url = $ApiPath . '/store/getServiceCountList/'.$storeId.'/'.$dateType.'/'.$page.'/'.$perPage.'?startDate='.$start_time.'&endDate='.$end_time;
        }  else {
            $url = $ApiPath . '/store/getServiceCountList/'.$storeId.'/'.$dateType.'/'.$page.'/'.$perPage;
        }
        $ApiPath = config('appconfig.ApiPath8890');
        $relust = Utils::curlPost1($url);
        return $relust;
    }
    
    /*
     * 设置店铺营业时间
     * author xfwed 
     * date 2021.05.31
     */

    public function saveOpenTime() {
        $store_id = input('param.store_id');
        $open_time = input('param.open_time');
        
        $row = Store::where('id',$store_id)->update([
            'open_time'=>$open_time,
                ]);
        if($row){
            return $this->ajaxReturn(0, '设置成功', null);
        }  else {
            return $this->ajaxReturn(3, '设置失败', null);
        }
        
    }
    
    


}
